<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="chrome=1">
    
    <title>【深入浅出jQuery】源码浅析2--奇技淫巧 | Coco ’s blog</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
    
    <meta name="author" content="Coco">
    
    
    <meta name="keywords" content="jQuery源码分析, jQuery源码, jQuery框架, jQuery架构">
    <meta name="description" content="最近一直在研读 jQuery 源码，初看源码一头雾水毫无头绪，真正静下心来细看写的真是精妙，让你感叹代码之美。其结构明晰，高内聚、低耦合，兼具优秀的性能与便利的扩展性，在浏览器的兼容性（功能缺陷、渐进增强）优雅的处理能力以及 Ajax 等方面周到而强大的定制功能无不令人惊叹。">
<meta property="og:type" content="article">
<meta property="og:title" content="【深入浅出jQuery】源码浅析2--奇技淫巧 | Coco ’s blog">
<meta property="og:url" content="http://sbco.cc/2016/03/20/jQ2/index.html">
<meta property="og:site_name" content="Coco ’s blog">
<meta property="og:description" content="最近一直在研读 jQuery 源码，初看源码一头雾水毫无头绪，真正静下心来细看写的真是精妙，让你感叹代码之美。其结构明晰，高内聚、低耦合，兼具优秀的性能与便利的扩展性，在浏览器的兼容性（功能缺陷、渐进增强）优雅的处理能力以及 Ajax 等方面周到而强大的定制功能无不令人惊叹。">
<meta property="og:updated_time" content="2016-06-03T10:01:54.802Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="【深入浅出jQuery】源码浅析2--奇技淫巧 | Coco ’s blog">
<meta name="twitter:description" content="最近一直在研读 jQuery 源码，初看源码一头雾水毫无头绪，真正静下心来细看写的真是精妙，让你感叹代码之美。其结构明晰，高内聚、低耦合，兼具优秀的性能与便利的扩展性，在浏览器的兼容性（功能缺陷、渐进增强）优雅的处理能力以及 Ajax 等方面周到而强大的定制功能无不令人惊叹。">
    
    <link rel="icon" type="image/x-icon" href="/favicon.png">
    <link rel="stylesheet" href="/css/uno.css">
    <link rel="stylesheet" href="/css/highlight.css">
    <link rel="stylesheet" href="/css/archive.css">
    <link rel="stylesheet" href="/css/china-social-icon.css">
</head>
<body>
    <span class="mobile btn-mobile-menu">
      <i class="icon icon-list btn-mobile-menu__icon"></i>
      <i class="icon icon-x-circle btn-mobile-close__icon hidden"></i>
    </span>
    
<header class="panel-cover panel-cover--collapsed">

  <div class="panel-main">
    <div class="panel-main__inner panel-inverted">
    <div class="panel-main__content">
        
        <img src="/images/logo.png" alt="Coco ’s blog logo" class="panel-cover__logo logo" title="Click Me!!!"/>
        
        <h1 class="panel-cover__title panel-title"><a href="/" title="link to homepage">Coco ’s blog</a></h1>
        <hr class="panel-cover__divider" />
        
        <p class="panel-cover__description">
          少年不知愁滋味 为赋新词强说愁
        </p>
        <hr class="panel-cover__divider panel-cover__divider--secondary" />
        
        <div class="navigation-wrapper">
          <nav class="cover-navigation cover-navigation--primary">
            <ul class="navigation">
              
                
                <li class="navigation__item"><a href="/#blog" title="" class="blog-button">首页</a></li>
              
                
                <li class="navigation__item"><a href="/about/html/" title="" class="">关于</a></li>
              
                
                <li class="navigation__item"><a href="/archive" title="" class="">归档</a></li>
              
              <a target="_blank" href="https://github.com/chokcoco"><li class='navigation__item github' title="To my Github"></li></a>
              <a target="_blank" href="http://www.cnblogs.com/coco1s/"> <li class='navigation__item'><div class='navigation__item blog' title="To my cnblogs"></div></li></a>
            </ul>
          </nav>
          <!-- ----------------------------
To add a new social icon simply duplicate one of the list items from below
and change the class in the <i> tag to match the desired social network
and then add your link to the <a>. Here is a full list of social network
classes that you can use:
    icon-social-500px
    icon-social-behance
    icon-social-delicious
    icon-social-designer-news
    icon-social-deviant-art
    icon-social-digg
    icon-social-dribbble
    icon-social-facebook
    icon-social-flickr
    icon-social-forrst
    icon-social-foursquare
    icon-social-github
    icon-social-google-plus
    icon-social-hi5
    icon-social-instagram
    icon-social-lastfm
    icon-social-linkedin
    icon-social-medium
    icon-social-myspace
    icon-social-path
    icon-social-pinterest
    icon-social-rdio
    icon-social-reddit
    icon-social-skype
    icon-social-spotify
    icon-social-stack-overflow
    icon-social-steam
    icon-social-stumbleupon
    icon-social-treehouse
    icon-social-tumblr
    icon-social-twitter
    icon-social-vimeo
    icon-social-xbox
    icon-social-yelp
    icon-social-youtube
    icon-social-zerply
    icon-mail
-------------------------------->
<!-- add social info here -->


        </div>
      </div>
    </div>
    <div class="panel-cover--overlay"></div>
  </div>
</header>

    <div class="content-wrapper">
      <div class="content-wrapper__inner entry">
        
<article class="post-container post-container--single">
  <header class="post-header">
    <h1 class="post-title">【深入浅出jQuery】源码浅析2--奇技淫巧</h1>
    
    <div class="post-meta">
      <time datetime="2016-03-20" class="post-meta__date date">2016-03-20</time>
      <span id="busuanzi_container_page_pv">
        • 阅读量（<span id="busuanzi_value_page_pv"></span>）
      </span>
      <span class="post-meta__tags tags">
          
          
             &#8226; 标签:
            <font class="tags">
              <a class="tags-link" href="/tags/jQuery源码分析/">jQuery源码分析</a>
            </font>
          
      </span>

    </div>
    
  </header>

  <section id="post-content" class="article-content post">
    <p>最近一直在研读 jQuery 源码，初看源码一头雾水毫无头绪，真正静下心来细看写的真是精妙，让你感叹代码之美。</p><p>其结构明晰，高内聚、低耦合，兼具优秀的性能与便利的扩展性，在浏览器的兼容性（功能缺陷、渐进增强）优雅的处理能力以及 Ajax 等方面周到而强大的定制功能无不令人惊叹。<a id="more"></a></p><p>另外，阅读源码让我接触到了大量底层的知识。对原生JS 、框架设计、代码优化有了全新的认识，接下来将会写一系列关于 jQuery 解析的文章。</p><p>我在 github 上关于 jQuery 源码的全文注解，感兴趣的可以围观一下。 <a href="https://github.com/chokcoco/jQuery-" target="_blank" rel="external">jQuery v1.10.2 源码注解 </a>。</p><p>系列第一篇： <a href="http://www.cnblogs.com/coco1s/p/5261646.html" target="_blank" rel="external">【深入浅出jQuery】源码浅析–整体架构</a></p><p>本篇是系列第二篇，标题起得有点大，希望内容对得起这个标题，这篇文章主要总结一下在 jQuery 中一些十分讨巧的 coding 方式，将会由浅及深，可能会有一些基础，但是我希望全面一点，对看文章的人都有所帮助，源码我还一直在阅读，也会不断的更新本文。</p><p>即便你不想去阅读源码，看看下面的总结，我想对提高编程能力，转换思维方式都大有裨益，废话少说，进入正题。</p><h2 id="短路表达式-与-多重短路表达式"><a href="#短路表达式-与-多重短路表达式" class="headerlink" title="短路表达式 与 多重短路表达式"></a>短路表达式 与 多重短路表达式</h2><p>短路表达式这个应该人所皆知了。在 jQuery 中，大量的使用了短路表达式与多重短路表达式。</p><p>短路表达式：作为”&amp;&amp;”和”||”操作符的操作数表达式，这些表达式在进行求值时，只要最终的结果已经可以确定是真或假，求值过程便告终止，这称之为短路求值。这是这两个操作符的一个重要属性。<br></p><figure class="highlight javascript"><table><tr><td class="gutter"><pre>
            <span class="line">1</span>
            <br>
            <span class="line">2</span>
            <br>
            <span class="line">3</span>
            <br>
            <span class="line">4</span>
            <br>
            <span class="line">5</span>
            <br>
            <span class="line">6</span>
            <br>
            <span class="line">7</span>
            <br>
            <span class="line">8</span>
            <br>
            <span class="line">9</span>
            <br>
            <span class="line">10</span>
            <br>
            <span class="line">11</span>
            <br>
            <span class="line">12</span>
            <br>
            <span class="line">13</span>
            <br>
            <span class="line">14</span>
            <br>
            <span class="line">15</span>
            <br>
            <span class="line">16</span>
            <br>
            <span class="line">17</span>
            <br>
          </pre></td><td class="code"><pre>
            <span class="line">
              <span class="comment">// ||短路表达式</span>
            </span>
            <br>
            <span class="line">
              <span class="keyword">var</span> foo = a || b;</span>
            <br>
            <span class="line">
              <span class="comment">// 相当于</span>
            </span>
            <br>
            <span class="line">
              <span class="keyword">if</span>(a)&#123;</span>
            <br>
            <span class="line"> foo = a;</span>
            <br>
            <span class="line">&#125;
              <span class="keyword">else</span>&#123;</span>
            <br>
            <span class="line"> foo = b;</span>
            <br>
            <span class="line">&#125;</span>
            <br>
            <span class="line"></span>
            <br>
            <span class="line">
              <span class="comment">// &amp;amp;短路表达式</span>
            </span>
            <br>
            <span class="line">
              <span class="keyword">var</span> bar = a &amp;amp;&amp;amp; b;</span>
            <br>
            <span class="line">
              <span class="comment">// 相当于</span>
            </span>
            <br>
            <span class="line">
              <span class="keyword">if</span>(a)&#123;</span>
            <br>
            <span class="line"> bar = b;</span>
            <br>
            <span class="line">&#125;
              <span class="keyword">else</span>&#123;</span>
            <br>
            <span class="line"> bar = a;</span>
            <br>
            <span class="line">&#125;</span>
            <br>
          </pre></td></tr></table></figure><p></p><p>当然，上面两个例子是短路表达式最简单是情况，多数情况下，jQuery 是这样使用它们的：<br></p><figure class="highlight javascript"><table><tr><td class="gutter"><pre>
            <span class="line">1</span>
            <br>
            <span class="line">2</span>
            <br>
            <span class="line">3</span>
            <br>
            <span class="line">4</span>
            <br>
            <span class="line">5</span>
            <br>
            <span class="line">6</span>
            <br>
            <span class="line">7</span>
            <br>
            <span class="line">8</span>
            <br>
            <span class="line">9</span>
            <br>
          </pre></td><td class="code"><pre>
            <span class="line">
              <span class="comment">// 选自 jQuery 源码中的 Sizzle 部分</span>
            </span>
            <br>
            <span class="line">
              <span class="function">
                <span class="keyword">function</span>
                <span class="title">siblingCheck</span>(
                <span class="params">a, b</span>) </span>&#123;</span>
            <br>
            <span class="line">
              <span class="keyword">var</span> cur = b &amp;amp; a,</span>
            <br>
            <span class="line"> diff = cur &amp;amp;&amp;amp; a.nodeType ===
              <span class="number">1</span> &amp;amp;&amp;amp; b.nodeType ===
              <span class="number">1</span> &amp;amp;&amp;amp;</span>
            <br>
            <span class="line"> (~b.sourceIndex || MAX_NEGATIVE) -</span>
            <br>
            <span class="line"> (~a.sourceIndex || MAX_NEGATIVE);</span>
            <br>
            <span class="line"></span>
            <br>
            <span class="line">
              <span class="comment">// other code ...</span>
            </span>
            <br>
            <span class="line">&#125;</span>
            <br>
          </pre></td></tr></table></figure><p></p><p>嗯，可以看到，diff 的值经历了多重短路表达式配合一些全等判断才得出，这种代码很优雅，但是可读性下降了很多，使用的时候权衡一下，多重短路表达式和简单短路表达式其实一样，只需要先把后面的当成一个整体，依次推进，得出最终值。<br></p><figure class="highlight javascript"><table><tr><td class="gutter"><pre>
            <span class="line">1</span>
            <br>
            <span class="line">2</span>
            <br>
            <span class="line">3</span>
            <br>
            <span class="line">4</span>
            <br>
          </pre></td><td class="code"><pre>
            <span class="line">
              <span class="keyword">var</span> a =
              <span class="number">1</span>, b =
              <span class="number">0</span>, c =
              <span class="number">3</span>;</span>
            <br>
            <span class="line"></span>
            <br>
            <span class="line">
              <span class="keyword">var</span> foo = a &amp;amp; b &amp;amp;&amp;amp; c,
              <span class="comment">// 0 ,相当于 a &amp;amp;&amp;amp; (b &amp;amp;&amp;amp; c)</span>
            </span>
            <br>
            <span class="line"> bar = a || b || c;
              <span class="comment">// 1</span>
            </span>
            <br>
          </pre></td></tr></table></figure><p></p><p>这里需要提出一些值得注意的点：</p><p>1、在 Javascript 的逻辑运算中，0、””、null、false、undefined、NaN 都会判定为 false ，而其他都为 true</p><p>2、因为 Javascript 的内置弱类型域 (weak-typing domain)，所以对严格的输入验证这一点不太在意，即便使用 &amp;&amp; 或者 || 运算符的运算数不是布尔值，仍然可以将它看作布尔运算。虽然如此，还是建议如下：<br></p><figure class="highlight javascript"><table><tr><td class="gutter"><pre>
            <span class="line">1</span>
            <br>
            <span class="line">2</span>
            <br>
          </pre></td><td class="code"><pre>
            <span class="line">
              <span class="keyword">if</span>(foo)&#123; ... &#125;
              <span class="comment">//不够严谨</span>
            </span>
            <br>
            <span class="line">
              <span class="keyword">if</span>(!!foo)&#123; ... &#125;
              <span class="comment">//更为严谨，!!可将其他类型的值转换为boolean类型</span>
            </span>
            <br>
          </pre></td></tr></table></figure><p></p><p>注重细节，JavaScript 既不弱也不低等，我们只是需要更努力一点工作以使我们的代码变得真正健壮。</p><h2 id="预定义常用方法的入口"><a href="#预定义常用方法的入口" class="headerlink" title="预定义常用方法的入口"></a>预定义常用方法的入口</h2><p>在 jQuery 的头几十行，有这么一段有趣的代码：<br></p><figure class="highlight javascript"><table><tr><td class="gutter"><pre>
            <span class="line">1</span>
            <br>
            <span class="line">2</span>
            <br>
            <span class="line">3</span>
            <br>
            <span class="line">4</span>
            <br>
            <span class="line">5</span>
            <br>
            <span class="line">6</span>
            <br>
            <span class="line">7</span>
            <br>
            <span class="line">8</span>
            <br>
            <span class="line">9</span>
            <br>
            <span class="line">10</span>
            <br>
            <span class="line">11</span>
            <br>
            <span class="line">12</span>
            <br>
            <span class="line">13</span>
            <br>
            <span class="line">14</span>
            <br>
            <span class="line">15</span>
            <br>
            <span class="line">16</span>
            <br>
            <span class="line">17</span>
            <br>
          </pre></td><td class="code"><pre>
            <span class="line">(
              <span class="function">
                <span class="keyword">function</span>(
                <span class="params">window, undefined</span>) </span>&#123;</span>
            <br>
            <span class="line">
              <span class="keyword">var</span>
            </span>
            <br>
            <span class="line">
              <span class="comment">// 定义了一个对象变量，一个字符串变量，一个数组变量</span>
            </span>
            <br>
            <span class="line"> class2type = &#123;&#125;,</span>
            <br>
            <span class="line"> core_version =
              <span class="string">"1.10.2"</span>,</span>
            <br>
            <span class="line"> core_deletedIds = [],</span>
            <br>
            <span class="line"></span>
            <br>
            <span class="line">
              <span class="comment">// 保存了对象、字符串、数组的一些常用方法 concat push 等等...</span>
            </span>
            <br>
            <span class="line"> core_concat = core_deletedIds.concat,</span>
            <br>
            <span class="line"> core_push = core_deletedIds.push,</span>
            <br>
            <span class="line"> core_slice = core_deletedIds.slice,</span>
            <br>
            <span class="line"> core_indexOf = core_deletedIds.indexOf,</span>
            <br>
            <span class="line"> core_toString = class2type.toString,</span>
            <br>
            <span class="line"> core_hasOwn = class2type.hasOwnProperty,</span>
            <br>
            <span class="line"> core_trim = core_version.trim;</span>
            <br>
            <span class="line"></span>
            <br>
            <span class="line">&#125;)(
              <span class="built_in">window</span>);</span>
            <br>
          </pre></td></tr></table></figure><p></p><p>不得不说，jQuery 在细节上做的真的很好，这里首先定义了一个对象变量、一个字符串变量、数组变量，要注意这 3 个变量本身在下文是有自己的用途的（可以看到，jQuery 作者惜字如金，真的是去压榨每一个变量的作用，使其作用最大化）。</p><p>其次，借用这三个变量，再定义些常用的核心方法，从上往下是数组的 concat、push 、slice 、indexOf 方法，对象的 toString 、hasOwnProperty 方法以及字符串的 trim 方法，core_xxxx 这几个变量事先存储好了这些常用方法的入口，如果下文行文当中需要调用这些方法，将会：<br></p><figure class="highlight javascript"><table><tr><td class="gutter"><pre>
            <span class="line">1</span>
            <br>
            <span class="line">2</span>
            <br>
            <span class="line">3</span>
            <br>
            <span class="line">4</span>
            <br>
            <span class="line">5</span>
            <br>
            <span class="line">6</span>
            <br>
            <span class="line">7</span>
            <br>
            <span class="line">8</span>
            <br>
            <span class="line">9</span>
            <br>
            <span class="line">10</span>
            <br>
          </pre></td><td class="code"><pre>
            <span class="line">jQuery.fn = jQuery.prototype = &#123;</span>
            <br>
            <span class="line">
              <span class="comment">// ...</span>
            </span>
            <br>
            <span class="line"></span>
            <br>
            <span class="line">
              <span class="comment">// 将 jQuery 对象转换成数组类型</span>
            </span>
            <br>
            <span class="line"> toArray:
              <span class="function">
                <span class="keyword">function</span>(
                <span class="params"></span>) </span>&#123;</span>
            <br>
            <span class="line">
              <span class="comment">// 调用数组的 slice 方法，使用预先定义好了的 core_slice ，节省查找内存地址时间，提高效率</span>
            </span>
            <br>
            <span class="line">
              <span class="comment">// 相当于 return Array.prototype.slice.call(this)</span>
            </span>
            <br>
            <span class="line">
              <span class="keyword">return</span> core_slice.call(
              <span class="keyword">this</span>);</span>
            <br>
            <span class="line"> &#125;</span>
            <br>
            <span class="line">&#125;</span>
            <br>
          </pre></td></tr></table></figure><p></p><p>可以看到，当需要使用这些预先定义好的方法，只需要借助 call 或者 apply（ <a href="http://www.cnblogs.com/coco1s/p/4833199.html" target="_blank" rel="external">戳我详解</a>）进行调用。</p><p>那么 jQuery 为什么要这样做呢，我觉得：</p><ul><li><p>以数组对象的 concat 方法为例，如果不预先定义好 core_concat = core_deletedIds.concat 而是调用实例 arr 的方法 concat 时，首先需要辨别当前实例 arr 的类型是 Array，在内存空间中寻找 Array 的 concat 内存入口，把当前对象 arr 的指针和其他参数压入栈，跳转到 concat 地址开始执行，而当保存了 concat 方法的入口 core_concat 时，完全就可以省去前面两个步骤，从而提升一些性能；</p></li><li><p>另外一点，借助 call 或者 apply 的方式调用，让一些类数组可以直接调用数组的方法。就如上面是示例，jQuery 对象是类数组类型，可以直接调用数组的 slice 方法转换为数组类型。又譬如，将参数 arguments 转换为数组类型：</p><figure class="highlight javascript"><table><tr><td class="gutter"><pre>
              <span class="line">1</span>
              <br>
              <span class="line">2</span>
              <br>
              <span class="line">3</span>
              <br>
              <span class="line">4</span>
              <br>
              <span class="line">5</span>
              <br>
              <span class="line">6</span>
              <br>
              <span class="line">7</span>
              <br>
            </pre></td><td class="code"><pre>
              <span class="line">
                <span class="function">
                  <span class="keyword">function</span>
                  <span class="title">test</span>(
                  <span class="params">a,b,c</span>)</span>&#123;</span>
              <br>
              <span class="line">
                <span class="comment">// 将参数 arguments 转换为数组</span>
              </span>
              <br>
              <span class="line">
                <span class="comment">// 使之可以调用数组成员方法</span>
              </span>
              <br>
              <span class="line">
                <span class="keyword">var</span> arr =
                <span class="built_in">Array</span>.prototype.slice.call(
                <span class="built_in">arguments</span>);</span>
              <br>
              <span class="line"></span>
              <br>
              <span class="line"> ...</span>
              <br>
              <span class="line">&#125;</span>
              <br>
            </pre></td></tr></table></figure></li></ul><h2 id="钩子机制（hook）"><a href="#钩子机制（hook）" class="headerlink" title="钩子机制（hook）"></a>钩子机制（hook）</h2><p>在 jQuery 2.0.0 之前的版本，对兼容性做了大量的处理，正是这样才让广大开发人员能够忽略不同浏览器的不同特性的专注于业务本身的逻辑。而其中，钩子机制在浏览器兼容方面起了十分巨大的作用。</p><p>钩子是编程惯用的一种手法，用来解决一种或多种特殊情况的处理。</p><p>简单来说，钩子就是适配器原理，或者说是表驱动原理，我们预先定义了一些钩子，在正常的代码逻辑中使用钩子去适配一些特殊的属性，样式或事件，这样可以让我们少写很多 else if 语句。</p><p>如果还是很难懂，看一个简单的例子，举例说明 hook 到底如何使用：</p><p>现在考公务员，要么靠实力，要么靠关系，但领导肯定也不会弄的那么明显，一般都是暗箱操作，这个场景用钩子实现再合理不过了。<br></p><figure class="highlight javascript"><table><tr><td class="gutter"><pre>
            <span class="line">1</span>
            <br>
            <span class="line">2</span>
            <br>
            <span class="line">3</span>
            <br>
            <span class="line">4</span>
            <br>
            <span class="line">5</span>
            <br>
            <span class="line">6</span>
            <br>
            <span class="line">7</span>
            <br>
            <span class="line">8</span>
            <br>
            <span class="line">9</span>
            <br>
            <span class="line">10</span>
            <br>
            <span class="line">11</span>
            <br>
            <span class="line">12</span>
            <br>
            <span class="line">13</span>
            <br>
            <span class="line">14</span>
            <br>
            <span class="line">15</span>
            <br>
            <span class="line">16</span>
            <br>
            <span class="line">17</span>
            <br>
            <span class="line">18</span>
            <br>
            <span class="line">19</span>
            <br>
            <span class="line">20</span>
            <br>
            <span class="line">21</span>
            <br>
            <span class="line">22</span>
            <br>
            <span class="line">23</span>
            <br>
            <span class="line">24</span>
            <br>
            <span class="line">25</span>
            <br>
            <span class="line">26</span>
            <br>
            <span class="line">27</span>
            <br>
            <span class="line">28</span>
            <br>
            <span class="line">29</span>
            <br>
            <span class="line">30</span>
            <br>
            <span class="line">31</span>
            <br>
            <span class="line">32</span>
            <br>
            <span class="line">33</span>
            <br>
            <span class="line">34</span>
            <br>
            <span class="line">35</span>
            <br>
            <span class="line">36</span>
            <br>
            <span class="line">37</span>
            <br>
            <span class="line">38</span>
            <br>
            <span class="line">39</span>
            <br>
            <span class="line">40</span>
            <br>
            <span class="line">41</span>
            <br>
          </pre></td><td class="code"><pre>
            <span class="line">
              <span class="comment">// 如果不用钩子的情况</span>
            </span>
            <br>
            <span class="line">
              <span class="comment">// 考生分数以及父亲名</span>
            </span>
            <br>
            <span class="line">
              <span class="function">
                <span class="keyword">function</span>
                <span class="title">examinee</span>(
                <span class="params">name, score, fatherName</span>) </span>&#123;</span>
            <br>
            <span class="line">
              <span class="keyword">return</span> &#123;</span>
            <br>
            <span class="line">        name: name,</span>
            <br>
            <span class="line">        score: score,</span>
            <br>
            <span class="line">        fatherName: fatherName</span>
            <br>
            <span class="line">    &#125;;</span>
            <br>
            <span class="line">&#125;</span>
            <br>
            <span class="line"></span>
            <br>
            <span class="line">
              <span class="comment">// 审阅考生们</span>
            </span>
            <br>
            <span class="line">
              <span class="function">
                <span class="keyword">function</span>
                <span class="title">judge</span>(
                <span class="params">examinees</span>) </span>&#123;</span>
            <br>
            <span class="line">
              <span class="keyword">var</span> result = &#123;&#125;;</span>
            <br>
            <span class="line">
              <span class="keyword">for</span> (
              <span class="keyword">var</span> i
              <span class="keyword">in</span> examinees) &#123;</span>
            <br>
            <span class="line">
              <span class="keyword">var</span> curExaminee = examinees[i];</span>
            <br>
            <span class="line">
              <span class="keyword">var</span> ret = curExaminee.score;</span>
            <br>
            <span class="line">
              <span class="comment">// 判断是否有后门关系</span>
            </span>
            <br>
            <span class="line">
              <span class="keyword">if</span> (curExaminee.fatherName ===
              <span class="string">'xijingping'</span>) &#123;</span>
            <br>
            <span class="line">            ret +=
              <span class="number">1000</span>;</span>
            <br>
            <span class="line">        &#125;
              <span class="keyword">else</span>
              <span class="keyword">if</span> (curExaminee.fatherName ===
              <span class="string">'ligang'</span>) &#123;</span>
            <br>
            <span class="line">            ret +=
              <span class="number">100</span>;</span>
            <br>
            <span class="line">        &#125;
              <span class="keyword">else</span>
              <span class="keyword">if</span> (curExaminee.fatherName ===
              <span class="string">'pengdehuai'</span>) &#123;</span>
            <br>
            <span class="line">            ret +=
              <span class="number">50</span>;</span>
            <br>
            <span class="line">        &#125;</span>
            <br>
            <span class="line">        result[curExaminee.name] = ret;</span>
            <br>
            <span class="line">    &#125;</span>
            <br>
            <span class="line">
              <span class="keyword">return</span> result;</span>
            <br>
            <span class="line">&#125;</span>
            <br>
            <span class="line"></span>
            <br>
            <span class="line">
              <span class="keyword">var</span> lihao = examinee(
              <span class="string">"lihao"</span>,
              <span class="number">10</span>,
              <span class="string">'ligang'</span>);</span>
            <br>
            <span class="line">
              <span class="keyword">var</span> xida = examinee(
              <span class="string">'xida'</span>,
              <span class="number">8</span>,
              <span class="string">'xijinping'</span>);</span>
            <br>
            <span class="line">
              <span class="keyword">var</span> peng = examinee(
              <span class="string">'peng'</span>,
              <span class="number">60</span>,
              <span class="string">'pengdehuai'</span>);</span>
            <br>
            <span class="line">
              <span class="keyword">var</span> liaoxiaofeng = examinee(
              <span class="string">'liaoxiaofeng'</span>,
              <span class="number">100</span>,
              <span class="string">'liaodaniu'</span>);</span>
            <br>
            <span class="line"></span>
            <br>
            <span class="line">
              <span class="keyword">var</span> result = judge([lihao, xida, peng, liaoxiaofeng]);</span>
            <br>
            <span class="line"></span>
            <br>
            <span class="line">
              <span class="comment">// 根据分数选取前三名</span>
            </span>
            <br>
            <span class="line">
              <span class="keyword">for</span> (
              <span class="keyword">var</span> name
              <span class="keyword">in</span> result) &#123;</span>
            <br>
            <span class="line">
              <span class="built_in">console</span>.log(
              <span class="string">"name:"</span> + name);</span>
            <br>
            <span class="line">
              <span class="built_in">console</span>.log(
              <span class="string">"score:"</span> + score);</span>
            <br>
            <span class="line">&#125;</span>
            <br>
          </pre></td></tr></table></figure><p></p><p>可以看到，在中间审阅考生这个函数中，运用了很多 else if 来判断是否考生有后门关系，如果现在业务场景发生变化，又多了几名考生，那么 else if 势必越来越复杂，往后维护代码也将越来越麻烦，成本很大，那么这个时候如果使用钩子机制，该如何做呢？<br></p><figure class="highlight javascript"><table><tr><td class="gutter"><pre>
            <span class="line">1</span>
            <br>
            <span class="line">2</span>
            <br>
            <span class="line">3</span>
            <br>
            <span class="line">4</span>
            <br>
            <span class="line">5</span>
            <br>
            <span class="line">6</span>
            <br>
            <span class="line">7</span>
            <br>
            <span class="line">8</span>
            <br>
            <span class="line">9</span>
            <br>
            <span class="line">10</span>
            <br>
            <span class="line">11</span>
            <br>
            <span class="line">12</span>
            <br>
            <span class="line">13</span>
            <br>
            <span class="line">14</span>
            <br>
            <span class="line">15</span>
            <br>
            <span class="line">16</span>
            <br>
            <span class="line">17</span>
            <br>
            <span class="line">18</span>
            <br>
            <span class="line">19</span>
            <br>
            <span class="line">20</span>
            <br>
            <span class="line">21</span>
            <br>
            <span class="line">22</span>
            <br>
            <span class="line">23</span>
            <br>
            <span class="line">24</span>
            <br>
            <span class="line">25</span>
            <br>
            <span class="line">26</span>
            <br>
            <span class="line">27</span>
            <br>
            <span class="line">28</span>
            <br>
            <span class="line">29</span>
            <br>
            <span class="line">30</span>
            <br>
            <span class="line">31</span>
            <br>
            <span class="line">32</span>
            <br>
            <span class="line">33</span>
            <br>
            <span class="line">34</span>
            <br>
            <span class="line">35</span>
            <br>
            <span class="line">36</span>
            <br>
            <span class="line">37</span>
            <br>
            <span class="line">38</span>
            <br>
            <span class="line">39</span>
            <br>
            <span class="line">40</span>
            <br>
            <span class="line">41</span>
            <br>
            <span class="line">42</span>
            <br>
            <span class="line">43</span>
            <br>
          </pre></td><td class="code"><pre>
            <span class="line">
              <span class="comment">// relationHook 是个钩子函数，用于得到关系得分</span>
            </span>
            <br>
            <span class="line">
              <span class="keyword">var</span> relationHook = &#123;</span>
            <br>
            <span class="line">
              <span class="string">"xijinping"</span>:
              <span class="number">1000</span>,</span>
            <br>
            <span class="line">
              <span class="string">"ligang"</span>:
              <span class="number">100</span>,</span>
            <br>
            <span class="line">
              <span class="string">"pengdehuai"</span>:
              <span class="number">50</span>,</span>
            <br>
            <span class="line">
              <span class="comment">// 新的考生只需要在钩子里添加关系分</span>
            </span>
            <br>
            <span class="line">&#125;</span>
            <br>
            <span class="line"></span>
            <br>
            <span class="line">
              <span class="comment">// 考生分数以及父亲名</span>
            </span>
            <br>
            <span class="line">
              <span class="function">
                <span class="keyword">function</span>
                <span class="title">examinee</span>(
                <span class="params">name, score, fatherName</span>) </span>&#123;</span>
            <br>
            <span class="line">
              <span class="keyword">return</span> &#123;</span>
            <br>
            <span class="line"> name: name,</span>
            <br>
            <span class="line"> score: score,</span>
            <br>
            <span class="line"> fatherName: fatherName</span>
            <br>
            <span class="line"> &#125;;</span>
            <br>
            <span class="line">&#125;</span>
            <br>
            <span class="line"></span>
            <br>
            <span class="line">
              <span class="comment">// 审阅考生们</span>
            </span>
            <br>
            <span class="line">
              <span class="function">
                <span class="keyword">function</span>
                <span class="title">judge</span>(
                <span class="params">examinees</span>) </span>&#123;</span>
            <br>
            <span class="line">
              <span class="keyword">var</span> result = &#123;&#125;;</span>
            <br>
            <span class="line">
              <span class="keyword">for</span> (
              <span class="keyword">var</span> i
              <span class="keyword">in</span> examinees) &#123;</span>
            <br>
            <span class="line">
              <span class="keyword">var</span> curExaminee = examinees[i];</span>
            <br>
            <span class="line">
              <span class="keyword">var</span> ret = curExaminee.score;</span>
            <br>
            <span class="line">
              <span class="keyword">if</span> (relationHook[curExaminee.fatherName] ) &#123;</span>
            <br>
            <span class="line"> ret += relationHook[curExaminee.fatherName] ;</span>
            <br>
            <span class="line"> &#125;</span>
            <br>
            <span class="line"> result[curExaminee.name] = ret;</span>
            <br>
            <span class="line"> &#125;</span>
            <br>
            <span class="line">
              <span class="keyword">return</span> result;</span>
            <br>
            <span class="line">&#125;</span>
            <br>
            <span class="line"></span>
            <br>
            <span class="line">
              <span class="keyword">var</span> lihao = examinee(
              <span class="string">"lihao"</span>,
              <span class="number">10</span>,
              <span class="string">'ligang'</span>);</span>
            <br>
            <span class="line">
              <span class="keyword">var</span> xida = examinee(
              <span class="string">'xida'</span>,
              <span class="number">8</span>,
              <span class="string">'xijinping'</span>);</span>
            <br>
            <span class="line">
              <span class="keyword">var</span> peng = examinee(
              <span class="string">'peng'</span>,
              <span class="number">60</span>,
              <span class="string">'pengdehuai'</span>);</span>
            <br>
            <span class="line">
              <span class="keyword">var</span> liaoxiaofeng = examinee(
              <span class="string">'liaoxiaofeng'</span>,
              <span class="number">100</span>,
              <span class="string">'liaodaniu'</span>);</span>
            <br>
            <span class="line"></span>
            <br>
            <span class="line">
              <span class="keyword">var</span> result = judge([lihao, xida, peng, liaoxiaofeng]);</span>
            <br>
            <span class="line"></span>
            <br>
            <span class="line">
              <span class="comment">// 根据分数选取前三名</span>
            </span>
            <br>
            <span class="line">
              <span class="keyword">for</span> (
              <span class="keyword">var</span> name
              <span class="keyword">in</span> result) &#123;</span>
            <br>
            <span class="line">
              <span class="built_in">console</span>.log(
              <span class="string">"name:"</span> + name);</span>
            <br>
            <span class="line">
              <span class="built_in">console</span>.log(
              <span class="string">"score:"</span> + score);</span>
            <br>
            <span class="line">&#125;</span>
            <br>
          </pre></td></tr></table></figure><p></p><p>可以看到，使用钩子去处理特殊情况，可以让代码的逻辑更加清晰，省去大量的条件判断，上面的钩子机制的实现方式，采用的就是表驱动方式，就是我们事先预定好一张表（俗称打表），用这张表去适配特殊情况。</p><p>当然 jQuery 的 hook 是一种更为抽象的概念，在不同场景可以用不同方式实现。</p><p>看看 jQuery 里的表驱动 hook 实现，$.type 方法：<br></p><figure class="highlight javascript"><table><tr><td class="gutter"><pre>
            <span class="line">1</span>
            <br>
            <span class="line">2</span>
            <br>
            <span class="line">3</span>
            <br>
            <span class="line">4</span>
            <br>
            <span class="line">5</span>
            <br>
            <span class="line">6</span>
            <br>
            <span class="line">7</span>
            <br>
            <span class="line">8</span>
            <br>
            <span class="line">9</span>
            <br>
            <span class="line">10</span>
            <br>
            <span class="line">11</span>
            <br>
            <span class="line">12</span>
            <br>
            <span class="line">13</span>
            <br>
            <span class="line">14</span>
            <br>
            <span class="line">15</span>
            <br>
            <span class="line">16</span>
            <br>
            <span class="line">17</span>
            <br>
            <span class="line">18</span>
            <br>
            <span class="line">19</span>
            <br>
            <span class="line">20</span>
            <br>
            <span class="line">21</span>
            <br>
            <span class="line">22</span>
            <br>
            <span class="line">23</span>
            <br>
            <span class="line">24</span>
            <br>
            <span class="line">25</span>
            <br>
            <span class="line">26</span>
            <br>
            <span class="line">27</span>
            <br>
            <span class="line">28</span>
            <br>
            <span class="line">29</span>
            <br>
          </pre></td><td class="code"><pre>
            <span class="line">(
              <span class="function">
                <span class="keyword">function</span>(
                <span class="params">window, undefined</span>) </span>&#123;</span>
            <br>
            <span class="line">
              <span class="keyword">var</span>
            </span>
            <br>
            <span class="line">
              <span class="comment">// 用于预存储一张类型表用于 hook</span>
            </span>
            <br>
            <span class="line"> class2type = &#123;&#125;;</span>
            <br>
            <span class="line"></span>
            <br>
            <span class="line">
              <span class="comment">// 原生的 typeof 方法并不能区分出一个变量它是 Array 、RegExp 等 object 类型，jQuery 为了扩展
                typeof 的表达力，因此有了 $.type 方法</span>
            </span>
            <br>
            <span class="line">
              <span class="comment">// 针对一些特殊的对象（例如 null，Array，RegExp）也进行精准的类型判断</span>
            </span>
            <br>
            <span class="line">
              <span class="comment">// 运用了钩子机制，判断类型前，将常见类型打表，先存于一个 Hash 表 class2type 里边</span>
            </span>
            <br>
            <span class="line"> jQuery.each(
              <span class="string">"Boolean Number String Function Array Date RegExp Object Error"</span>.split(
              <span class="string">" "</span>),
            <span class="function">
              <span class="keyword">function</span>(
              <span class="params">i, name</span>) </span>&#123;</span>
            <br>
            <span class="line"> class2type[
              <span class="string">"[object "</span> + name +
              <span class="string">"]"</span>] = name.toLowerCase();</span>
            <br>
            <span class="line"> &#125;);</span>
            <br>
            <span class="line"></span>
            <br>
            <span class="line"> jQuery.extend(&#123;</span>
            <br>
            <span class="line">
              <span class="comment">// 确定JavaScript 对象的类型</span>
            </span>
            <br>
            <span class="line">
              <span class="comment">// 这个方法的关键之处在于 class2type[core_toString.call(obj)]</span>
            </span>
            <br>
            <span class="line">
              <span class="comment">// 可以使得 typeof obj 为 "object" 类型的得到更进一步的精确判断</span>
            </span>
            <br>
            <span class="line"> type:
              <span class="function">
                <span class="keyword">function</span>(
                <span class="params">obj</span>) </span>&#123;</span>
            <br>
            <span class="line"></span>
            <br>
            <span class="line">
              <span class="keyword">if</span> (obj ==
              <span class="literal">null</span>) &#123;</span>
            <br>
            <span class="line">
              <span class="keyword">return</span>
              <span class="built_in">String</span>(obj);</span>
            <br>
            <span class="line"> &#125;</span>
            <br>
            <span class="line">
              <span class="comment">// 利用事先存好的 hash 表 class2type 作精准判断</span>
            </span>
            <br>
            <span class="line">
              <span class="comment">// 这里因为 hook 的存在，省去了大量的 else if 判断</span>
            </span>
            <br>
            <span class="line">
              <span class="keyword">return</span>
              <span class="keyword">typeof</span> obj ===
              <span class="string">"object"</span> ||
              <span class="keyword">typeof</span> obj ===
              <span class="string">"function"</span> ?</span>
            <br>
            <span class="line"> class2type[core_toString.call(obj)] ||
              <span class="string">"object"</span> :</span>
            <br>
            <span class="line">
              <span class="keyword">typeof</span> obj;</span>
            <br>
            <span class="line"> &#125;</span>
            <br>
            <span class="line"> &#125;)</span>
            <br>
            <span class="line">&#125;)(
              <span class="built_in">window</span>);</span>
            <br>
          </pre></td></tr></table></figure><p></p><p>这里的 hook 只是 jQuery 大量使用钩子的冰山一角，在对 DOM 元素的操作一块，attr 、val 、prop 、css 方法大量运用了钩子，用于兼容 IE 系列下的一些怪异行为。在遇到钩子函数的时候，要结合具体情境具体分析，这些钩子相对于表驱动而言更加复杂，它们的结构大体如下，只要记住钩子的核心原则，保持代码整体逻辑的流畅性，在特殊的情境下去处理一些特殊的情况：<br></p><figure class="highlight javascript"><table><tr><td class="gutter"><pre>
            <span class="line">1</span>
            <br>
            <span class="line">2</span>
            <br>
            <span class="line">3</span>
            <br>
            <span class="line">4</span>
            <br>
            <span class="line">5</span>
            <br>
            <span class="line">6</span>
            <br>
            <span class="line">7</span>
            <br>
            <span class="line">8</span>
            <br>
            <span class="line">9</span>
            <br>
          </pre></td><td class="code"><pre>
            <span class="line">
              <span class="keyword">var</span> someHook = &#123;</span>
            <br>
            <span class="line"> get:
              <span class="function">
                <span class="keyword">function</span>(
                <span class="params">elem</span>) </span>&#123;</span>
            <br>
            <span class="line">
              <span class="comment">// obtain and return a value</span>
            </span>
            <br>
            <span class="line">
              <span class="keyword">return</span>
              <span class="string">"something"</span>;</span>
            <br>
            <span class="line"> &#125;,</span>
            <br>
            <span class="line"> set:
              <span class="function">
                <span class="keyword">function</span>(
                <span class="params">elem, value</span>) </span>&#123;</span>
            <br>
            <span class="line">
              <span class="comment">// do something with value</span>
            </span>
            <br>
            <span class="line"> &#125;</span>
            <br>
            <span class="line">&#125;</span>
            <br>
          </pre></td></tr></table></figure><p></p><p>从某种程度上讲，钩子是一系列被设计为以你自己的代码来处理自定义值的回调函数。有了钩子，你可以将差不多任何东西保持在可控范围内。</p><h2 id="连贯接口"><a href="#连贯接口" class="headerlink" title="连贯接口"></a>连贯接口</h2><p>无论 jQuery 如今的流行趋势是否在下降，它用起来确实让人大呼过瘾，这很大程度归功于它的链式调用，接口的连贯性及易记性。很多人将连贯接口看成链式调用，这并不全面，我觉得连贯接口包含了链式调用且代表更多。而 jQuery 无疑是连贯接口的佼佼者。</p><h5 id="链式调用"><a href="#链式调用" class="headerlink" title="链式调用"></a>链式调用</h5><p>链式调用的主要思想就是使代码尽可能流畅易读，从而可以更快地被理解。有了链式调用，我们可以将代码组织为类似语句的片段，增强可读性的同时减少干扰。（ <a href="http://www.cnblogs.com/coco1s/p/5261646.html" target="_blank" rel="external">链式调用的具体实现上一章有详细讲到</a>）<br></p><figure class="highlight javascript"><table><tr><td class="gutter"><pre>
            <span class="line">1</span>
            <br>
            <span class="line">2</span>
            <br>
            <span class="line">3</span>
            <br>
            <span class="line">4</span>
            <br>
            <span class="line">5</span>
            <br>
            <span class="line">6</span>
            <br>
            <span class="line">7</span>
            <br>
            <span class="line">8</span>
            <br>
            <span class="line">9</span>
            <br>
            <span class="line">10</span>
            <br>
            <span class="line">11</span>
            <br>
            <span class="line">12</span>
            <br>
            <span class="line">13</span>
            <br>
            <span class="line">14</span>
            <br>
            <span class="line">15</span>
            <br>
          </pre></td><td class="code"><pre>
            <span class="line">
              <span class="comment">// 传统写法</span>
            </span>
            <br>
            <span class="line">
              <span class="keyword">var</span> elem =
              <span class="built_in">document</span>.getElementById(
              <span class="string">"foobar"</span>);</span>
            <br>
            <span class="line">elem.style.background =
              <span class="string">"red"</span>;</span>
            <br>
            <span class="line">elem.style.color =
              <span class="string">"green"</span>;</span>
            <br>
            <span class="line">elem.addEventListener(
              <span class="string">'click'</span>,
              <span class="function">
                <span class="keyword">function</span>(
                <span class="params">event</span>) </span>&#123;</span>
            <br>
            <span class="line"> alert(
              <span class="string">"hello world!"</span>);</span>
            <br>
            <span class="line">&#125;,
              <span class="literal">true</span>);</span>
            <br>
            <span class="line"></span>
            <br>
            <span class="line">
              <span class="comment">// jQuery 写法</span>
            </span>
            <br>
            <span class="line">$(
              <span class="string">'xxx'</span>)</span>
            <br>
            <span class="line"> .css(
              <span class="string">"background"</span>,
              <span class="string">"red"</span>)</span>
            <br>
            <span class="line"> .css(
              <span class="string">"color"</span>,
              <span class="string">"green"</span>)</span>
            <br>
            <span class="line"> .on(
              <span class="string">"click"</span>,
              <span class="function">
                <span class="keyword">function</span>(
                <span class="params">event</span>) </span>&#123;</span>
            <br>
            <span class="line"> 　　alert(
              <span class="string">"hello world"</span>);</span>
            <br>
            <span class="line"> &#125;);</span>
            <br>
          </pre></td></tr></table></figure><p></p><h5 id="命令查询同体"><a href="#命令查询同体" class="headerlink" title="命令查询同体"></a>命令查询同体</h5><p>这个上一章也讲过了，就是函数重载。正常而言，应该是命令查询分离（Command and Query Separation，CQS），是源于命令式编程的一个概念。那些改变对象的状态（内部的值）的函数称为命令，而那些检索值的函数称为查询。</p><p>原则上，查询函数返回数据，命令函数返回状态，各司其职。而 jQuery 将 getter 和 setter 方法压缩到单一方法中创建了一个连贯的接口，使得代码暴露更少的方法，但却以更少的代码实现同样的目标。</p><h5 id="参数映射及处理"><a href="#参数映射及处理" class="headerlink" title="参数映射及处理"></a>参数映射及处理</h5><p>jQuery 的接口连贯性还体现在了对参数的兼容处理上，方法如何接收数据比让它们具有可链性更为重要。</p><p>虽然方法的链式调用是非常普遍的，你可以很容易地在你的代码中实现，但是处理参数却不同，使用者可能传入各种奇怪的参数类型，而 jQuery 作者想的真的很周到，考虑了用户的多种使用场景，提供了多种对参数的处理。<br></p><figure class="highlight javascript"><table><tr><td class="gutter"><pre>
            <span class="line">1</span>
            <br>
            <span class="line">2</span>
            <br>
            <span class="line">3</span>
            <br>
            <span class="line">4</span>
            <br>
            <span class="line">5</span>
            <br>
            <span class="line">6</span>
            <br>
            <span class="line">7</span>
            <br>
            <span class="line">8</span>
            <br>
            <span class="line">9</span>
            <br>
            <span class="line">10</span>
            <br>
            <span class="line">11</span>
            <br>
            <span class="line">12</span>
            <br>
            <span class="line">13</span>
            <br>
            <span class="line">14</span>
            <br>
          </pre></td><td class="code"><pre>
            <span class="line">
              <span class="comment">// 传入键值对</span>
            </span>
            <br>
            <span class="line">jQuery(
              <span class="string">"#some-selector"</span>)</span>
            <br>
            <span class="line"> .css(
              <span class="string">"background"</span>,
              <span class="string">"red"</span>)</span>
            <br>
            <span class="line"> .css(
              <span class="string">"color"</span>,
              <span class="string">"white"</span>)</span>
            <br>
            <span class="line"> .css(
              <span class="string">"font-weight"</span>,
              <span class="string">"bold"</span>)</span>
            <br>
            <span class="line"> .css(
              <span class="string">"padding"</span>,
              <span class="number">10</span>);</span>
            <br>
            <span class="line"></span>
            <br>
            <span class="line">
              <span class="comment">// 传入 JSON 对象</span>
            </span>
            <br>
            <span class="line">jQuery(
              <span class="string">"#some-selector"</span>).css(&#123;</span>
            <br>
            <span class="line">
              <span class="string">"background"</span> :
              <span class="string">"red"</span>,</span>
            <br>
            <span class="line">
              <span class="string">"color"</span> :
              <span class="string">"white"</span>,</span>
            <br>
            <span class="line">
              <span class="string">"font-weight"</span> :
              <span class="string">"bold"</span>,</span>
            <br>
            <span class="line">
              <span class="string">"padding"</span> :
              <span class="number">10</span>
            </span>
            <br>
            <span class="line">&#125;);</span>
            <br>
          </pre></td></tr></table></figure><p></p><p>jQuery 的 on() 方法可以注册事件处理器。和 CSS() 一样它也可以接收一组映射格式的事件，但更进一步地，它允许单一处理器可以被多个事件注册：<br></p><figure class="highlight javascript"><table><tr><td class="gutter"><pre>
            <span class="line">1</span>
            <br>
            <span class="line">2</span>
            <br>
            <span class="line">3</span>
            <br>
            <span class="line">4</span>
            <br>
            <span class="line">5</span>
            <br>
            <span class="line">6</span>
            <br>
            <span class="line">7</span>
            <br>
            <span class="line">8</span>
            <br>
            <span class="line">9</span>
            <br>
          </pre></td><td class="code"><pre>
            <span class="line">
              <span class="comment">// binding events by passing a map</span>
            </span>
            <br>
            <span class="line">jQuery(
              <span class="string">"#some-selector"</span>).on(&#123;</span>
            <br>
            <span class="line">
              <span class="string">"click"</span> : myClickHandler,</span>
            <br>
            <span class="line">
              <span class="string">"keyup"</span> : myKeyupHandler,</span>
            <br>
            <span class="line">
              <span class="string">"change"</span> : myChangeHandler</span>
            <br>
            <span class="line">&#125;);</span>
            <br>
            <span class="line"></span>
            <br>
            <span class="line">
              <span class="comment">// binding a handler to multiple events:</span>
            </span>
            <br>
            <span class="line">jQuery(
              <span class="string">"#some-selector"</span>).on(
              <span class="string">"click keyup change"</span>, myEventHandler);</span>
            <br>
          </pre></td></tr></table></figure><p></p><h2 id="无-new-构造"><a href="#无-new-构造" class="headerlink" title="无 new 构造"></a>无 new 构造</h2><p>怎么访问 jQuery 类原型上的属性与方法，怎么做到做到既能隔离作用域还能使用 jQuery 原型对象的作用域呢？重点在于这一句：<br></p><figure class="highlight javascript"><table><tr><td class="gutter"><pre>
            <span class="line">1</span>
            <br>
            <span class="line">2</span>
            <br>
          </pre></td><td class="code"><pre>
            <span class="line">
              <span class="comment">// Give the init function the jQuery prototype for later instantiation</span>
            </span>
            <br>
            <span class="line">jQuery.fn.init.prototype = jQuery.fn;</span>
            <br>
          </pre></td></tr></table></figure><p></p><p>这里的关键就是通过原型传递解决问题，这一块上一章也讲过了，看过可以跳过了，将文字搬过来。</p><p>嘿，回想一下使用 jQuery 的时候，实例化一个 jQuery 对象的方法：<br></p><figure class="highlight javascript"><table><tr><td class="gutter"><pre>
            <span class="line">1</span>
            <br>
            <span class="line">2</span>
            <br>
            <span class="line">3</span>
            <br>
            <span class="line">4</span>
            <br>
            <span class="line">5</span>
            <br>
            <span class="line">6</span>
            <br>
          </pre></td><td class="code"><pre>
            <span class="line">
              <span class="comment">// 无 new 构造</span>
            </span>
            <br>
            <span class="line">$(
              <span class="string">'#test'</span>).text(
              <span class="string">'Test'</span>);</span>
            <br>
            <span class="line"></span>
            <br>
            <span class="line">
              <span class="comment">// 当然也可以使用 new</span>
            </span>
            <br>
            <span class="line">
              <span class="keyword">var</span> test =
              <span class="keyword">new</span> $(
              <span class="string">'#test'</span>);</span>
            <br>
            <span class="line">test.text(
              <span class="string">'Test'</span>);</span>
            <br>
          </pre></td></tr></table></figure><p></p><p>大部分人使用 jQuery 的时候都是使用第一种无 new 的构造方式，直接 $(‘’) 进行构造，这也是 jQuery 十分便捷的一个地方。当我们使用第一种无 new 构造方式的时候，其本质就是相当于 new jQuery()，那么在 jQuery 内部是如何实现的呢？看看：<br></p><figure class="highlight javascript"><table><tr><td class="gutter"><pre>
            <span class="line">1</span>
            <br>
            <span class="line">2</span>
            <br>
            <span class="line">3</span>
            <br>
            <span class="line">4</span>
            <br>
            <span class="line">5</span>
            <br>
            <span class="line">6</span>
            <br>
            <span class="line">7</span>
            <br>
            <span class="line">8</span>
            <br>
            <span class="line">9</span>
            <br>
            <span class="line">10</span>
            <br>
            <span class="line">11</span>
            <br>
            <span class="line">12</span>
            <br>
            <span class="line">13</span>
            <br>
            <span class="line">14</span>
            <br>
            <span class="line">15</span>
            <br>
            <span class="line">16</span>
            <br>
            <span class="line">17</span>
            <br>
            <span class="line">18</span>
            <br>
            <span class="line">19</span>
            <br>
            <span class="line">20</span>
            <br>
            <span class="line">21</span>
            <br>
            <span class="line">22</span>
            <br>
            <span class="line">23</span>
            <br>
            <span class="line">24</span>
            <br>
            <span class="line">25</span>
            <br>
          </pre></td><td class="code"><pre>
            <span class="line">(
              <span class="function">
                <span class="keyword">function</span>(
                <span class="params">window, undefined</span>) </span>&#123;</span>
            <br>
            <span class="line">
              <span class="keyword">var</span>
            </span>
            <br>
            <span class="line">
              <span class="comment">// ...</span>
            </span>
            <br>
            <span class="line"> jQuery =
              <span class="function">
                <span class="keyword">function</span>(
                <span class="params">selector, context</span>) </span>&#123;</span>
            <br>
            <span class="line">
              <span class="comment">// The jQuery object is actually just the init constructor 'enhanced'</span>
            </span>
            <br>
            <span class="line">
              <span class="comment">// 看这里，实例化方法 jQuery() 实际上是调用了其拓展的原型方法 jQuery.fn.init</span>
            </span>
            <br>
            <span class="line">
              <span class="keyword">return</span>
              <span class="keyword">new</span> jQuery.fn.init(selector, context, rootjQuery);</span>
            <br>
            <span class="line"> &#125;,</span>
            <br>
            <span class="line"></span>
            <br>
            <span class="line">
              <span class="comment">// jQuery.prototype 即是 jQuery 的原型，挂载在上面的方法，即可让所有生成的 jQuery 对象使用</span>
            </span>
            <br>
            <span class="line"> jQuery.fn = jQuery.prototype = &#123;</span>
            <br>
            <span class="line">
              <span class="comment">// 实例化化方法，这个方法可以称作 jQuery 对象构造器</span>
            </span>
            <br>
            <span class="line"> init:
              <span class="function">
                <span class="keyword">function</span>(
                <span class="params">selector, context, rootjQuery</span>) </span>&#123;</span>
            <br>
            <span class="line">
              <span class="comment">// ...</span>
            </span>
            <br>
            <span class="line"> &#125;</span>
            <br>
            <span class="line"> &#125;</span>
            <br>
            <span class="line">
              <span class="comment">// 这一句很关键，也很绕</span>
            </span>
            <br>
            <span class="line">
              <span class="comment">// jQuery 没有使用 new 运算符将 jQuery 实例化，而是直接调用其函数</span>
            </span>
            <br>
            <span class="line">
              <span class="comment">// 要实现这样,那么 jQuery 就要看成一个类，且返回一个正确的实例</span>
            </span>
            <br>
            <span class="line">
              <span class="comment">// 且实例还要能正确访问 jQuery 类原型上的属性与方法</span>
            </span>
            <br>
            <span class="line">
              <span class="comment">// jQuery 的方式是通过原型传递解决问题，把 jQuery 的原型传递给jQuery.prototype.init.prototype</span>
            </span>
            <br>
            <span class="line">
              <span class="comment">// 所以通过这个方法生成的实例 this 所指向的仍然是 jQuery.fn，所以能正确访问 jQuery 类原型上的属性与方法</span>
            </span>
            <br>
            <span class="line"> jQuery.fn.init.prototype = jQuery.fn;</span>
            <br>
            <span class="line"></span>
            <br>
            <span class="line">&#125;)(
              <span class="built_in">window</span>);</span>
            <br>
          </pre></td></tr></table></figure><p></p><p>大部分人初看 jQuery.fn.init.prototype = jQuery.fn 这一句都会被卡主，很是不解。但是这句真的算是 jQuery 的绝妙之处。理解这几句很重要，分点解析一下：</p><ol><li><p>首先要明确，使用 $(‘xxx’) 这种实例化方式，其内部调用的是 return new jQuery.fn.init(selector, context, rootjQuery) 这一句话，也就是构造实例是交给了 jQuery.fn.init() 方法取完成。</p></li><li><p>将 jQuery.fn.init 的 prototype 属性设置为 jQuery.fn，那么使用 new jQuery.fn.init() 生成的对象的原型对象就是 jQuery.fn ，所以挂载到 jQuery.fn 上面的函数就相当于挂载到 jQuery.fn.init() 生成的 jQuery 对象上，所有使用 new jQuery.fn.init() 生成的对象也能够访问到 jQuery.fn 上的所有原型方法。</p></li><li><p>也就是实例化方法存在这么一个关系链</p></li></ol><ul><li>jQuery.fn.init.prototype = jQuery.fn = jQuery.prototype ;</li><li>new jQuery.fn.init() 相当于 new jQuery() ;</li><li>jQuery() 返回的是 new jQuery.fn.init()，而 var obj = new jQuery()，所以这 2 者是相当的，所以我们可以无 new 实例化 jQuery 对象。</li></ul><h2 id="setTimeout"><a href="#setTimeout" class="headerlink" title="setTimeout"></a>setTimeout</h2><p>写到这里，发现上文的主题有些飘忽，接近于写成了 如何写出更好的 Javascript 代码，下面介绍一些 jQuery 中我觉得很棒的小技巧。</p><p>熟悉 jQuery 的人都知道 DOM Ready 事件，传Javascript原生的 window.onload 事件是在页面所有的资源都加载完毕后触发的。</p><p>如果页面上有大图片等资源响应缓慢, 会导致 window.onload 事件迟迟无法触发，所以出现了DOM Ready 事件。此事件在 DOM 文档结构准备完毕后触发，即在资源加载前触发。</p><p>另外我们需要在 DOM 准备完毕后，再修改DOM结构，比如添加DOM元素等。而为了完美实现 DOM Ready 事件，兼容各浏览器及低版本IE（针对高级的浏览器，可以使用 DOMContentLoaded 事件，省时省力），在 jQuery.ready() 方法里，运用了 setTimeout() 方法的一个特性， 在 setTimeout 中触发的函数, 一定是在 DOM 准备完毕后触发。<br></p><figure class="highlight javascript"><table><tr><td class="gutter"><pre>
            <span class="line">1</span>
            <br>
            <span class="line">2</span>
            <br>
            <span class="line">3</span>
            <br>
            <span class="line">4</span>
            <br>
            <span class="line">5</span>
            <br>
            <span class="line">6</span>
            <br>
            <span class="line">7</span>
            <br>
            <span class="line">8</span>
            <br>
            <span class="line">9</span>
            <br>
            <span class="line">10</span>
            <br>
            <span class="line">11</span>
            <br>
            <span class="line">12</span>
            <br>
            <span class="line">13</span>
            <br>
            <span class="line">14</span>
            <br>
            <span class="line">15</span>
            <br>
            <span class="line">16</span>
            <br>
            <span class="line">17</span>
            <br>
            <span class="line">18</span>
            <br>
            <span class="line">19</span>
            <br>
            <span class="line">20</span>
            <br>
            <span class="line">21</span>
            <br>
            <span class="line">22</span>
            <br>
            <span class="line">23</span>
            <br>
            <span class="line">24</span>
            <br>
            <span class="line">25</span>
            <br>
            <span class="line">26</span>
            <br>
            <span class="line">27</span>
            <br>
            <span class="line">28</span>
            <br>
            <span class="line">29</span>
            <br>
            <span class="line">30</span>
            <br>
            <span class="line">31</span>
            <br>
            <span class="line">32</span>
            <br>
            <span class="line">33</span>
            <br>
            <span class="line">34</span>
            <br>
            <span class="line">35</span>
            <br>
            <span class="line">36</span>
            <br>
            <span class="line">37</span>
            <br>
            <span class="line">38</span>
            <br>
            <span class="line">39</span>
            <br>
            <span class="line">40</span>
            <br>
            <span class="line">41</span>
            <br>
            <span class="line">42</span>
            <br>
            <span class="line">43</span>
            <br>
            <span class="line">44</span>
            <br>
            <span class="line">45</span>
            <br>
          </pre></td><td class="code"><pre>
            <span class="line">jQuery.extend(&#123;</span>
            <br>
            <span class="line"> ready:
              <span class="function">
                <span class="keyword">function</span>(
                <span class="params">wait</span>) </span>&#123;</span>
            <br>
            <span class="line">
              <span class="comment">// 如果需要等待，holdReady()的时候，把hold住的次数减1，如果还没到达0，说明还需要继续hold住，return掉</span>
            </span>
            <br>
            <span class="line">
              <span class="comment">// 如果不需要等待，判断是否已经Ready过了，如果已经ready过了，就不需要处理了。异步队列里边的done的回调都会执行了</span>
            </span>
            <br>
            <span class="line">
              <span class="keyword">if</span> (wait ===
              <span class="literal">true</span> ? --jQuery.readyWait : jQuery.isReady) &#123;</span>
            <br>
            <span class="line">
              <span class="keyword">return</span>;</span>
            <br>
            <span class="line"> &#125;</span>
            <br>
            <span class="line"></span>
            <br>
            <span class="line">
              <span class="comment">// 确定 body 存在</span>
            </span>
            <br>
            <span class="line">
              <span class="keyword">if</span> (!
              <span class="built_in">document</span>.body) &#123;</span>
            <br>
            <span class="line">
              <span class="comment">// 如果 body 还不存在 ，DOMContentLoaded 未完成，此时</span>
            </span>
            <br>
            <span class="line">
              <span class="comment">// 将 jQuery.ready 放入定时器 setTimeout 中</span>
            </span>
            <br>
            <span class="line">
              <span class="comment">// 不带时间参数的 setTimeout(a) 相当于 setTimeout(a,0)</span>
            </span>
            <br>
            <span class="line">
              <span class="comment">// 但是这里并不是立即触发 jQuery.ready</span>
            </span>
            <br>
            <span class="line">
              <span class="comment">// 由于 javascript 的单线程的异步模式</span>
            </span>
            <br>
            <span class="line">
              <span class="comment">// setTimeout(jQuery.ready) 会等到重绘完成才执行代码，也就是 DOMContentLoaded 之后才执行
                jQuery.ready</span>
            </span>
            <br>
            <span class="line">
              <span class="comment">// 所以这里有个小技巧：在 setTimeout 中触发的函数, 一定会在 DOM 准备完毕后触发</span>
            </span>
            <br>
            <span class="line">
              <span class="keyword">return</span> setTimeout(jQuery.ready);</span>
            <br>
            <span class="line"> &#125;</span>
            <br>
            <span class="line"></span>
            <br>
            <span class="line">
              <span class="comment">// Remember that the DOM is ready</span>
            </span>
            <br>
            <span class="line">
              <span class="comment">// 记录 DOM ready 已经完成</span>
            </span>
            <br>
            <span class="line"> jQuery.isReady =
              <span class="literal">true</span>;</span>
            <br>
            <span class="line"></span>
            <br>
            <span class="line">
              <span class="comment">// If a normal DOM Ready event fired, decrement, and wait if need be</span>
            </span>
            <br>
            <span class="line">
              <span class="comment">// wait 为 false 表示ready事情未触发过，否则 return</span>
            </span>
            <br>
            <span class="line">
              <span class="keyword">if</span> (wait !==
              <span class="literal">true</span> &amp;amp; --jQuery.readyWait &amp;gt;
              <span class="number">0</span>) &#123;</span>
            <br>
            <span class="line">
              <span class="keyword">return</span>;</span>
            <br>
            <span class="line"> &#125;</span>
            <br>
            <span class="line"></span>
            <br>
            <span class="line">
              <span class="comment">// If there are functions bound, to execute</span>
            </span>
            <br>
            <span class="line">
              <span class="comment">// 调用异步队列，然后派发成功事件出去（最后使用done接收，把上下文切换成document，默认第一个参数是jQuery。</span>
            </span>
            <br>
            <span class="line"> readyList.resolveWith(
              <span class="built_in">document</span>, [jQuery]);</span>
            <br>
            <span class="line"></span>
            <br>
            <span class="line">
              <span class="comment">// Trigger any bound ready events</span>
            </span>
            <br>
            <span class="line">
              <span class="comment">// 最后jQuery还可以触发自己的ready事件</span>
            </span>
            <br>
            <span class="line">
              <span class="comment">// 例如：</span>
            </span>
            <br>
            <span class="line">
              <span class="comment">// $(document).on('ready', fn2);</span>
            </span>
            <br>
            <span class="line">
              <span class="comment">// $(document).ready(fn1);</span>
            </span>
            <br>
            <span class="line">
              <span class="comment">// 这里的fn1会先执行，自己的ready事件绑定的fn2回调后执行</span>
            </span>
            <br>
            <span class="line">
              <span class="keyword">if</span> (jQuery.fn.trigger) &#123;</span>
            <br>
            <span class="line"> jQuery(
              <span class="built_in">document</span>).trigger(
              <span class="string">"ready"</span>).off(
              <span class="string">"ready"</span>);</span>
            <br>
            <span class="line"> &#125;</span>
            <br>
            <span class="line"> &#125;</span>
            <br>
            <span class="line">&#125;)</span>
            <br>
          </pre></td></tr></table></figure><p></p><p>暂且写这么多吧，技巧还有很多，诸如 $.Deferred() 异步队列的实现，jQuery 事件流机制等，篇幅较长，将会在以后慢慢详述。</p><p>原创文章，文笔有限，才疏学浅，文中若有不正之处，万望告知。</p><p>系列第一篇： <a href="http://www.cnblogs.com/coco1s/p/5261646.html" target="_blank" rel="external">【深入浅出jQuery】源码浅析–整体架构</a></p><p>最后，我在 github 上关于 jQuery 源码的全文注解，感兴趣的可以围观一下，给颗星星。 <a href="https://github.com/chokcoco/jQuery-" target="_blank" rel="external">jQuery v1.10.2 源码注解 </a>。</p>
  </section>

  
  

</article>


<!-- 多说评论框 start -->
  <div class="ds-thread" data-thread-key="post-jQ2" data-title="【深入浅出jQuery】源码浅析2--奇技淫巧" data-url="http://sbco.cc/2016/03/20/jQ2/"></div>
<!-- 多说评论框 end -->


        <footer class="footer">
	<div class="friendLink">友情链接：
		<ul>
			<li><a href="http://www.cnblogs.com/coco1s/">Coco</a></li>
			<li><a href="http://www.chengfeilong.com/">Scott's Blog</a></li>
			<li><a href="http://www.52cik.com/">楼教主</a></li>
			<li><a href="http://blog.aisuso.com/">姚嘉鑫博客</a></li>
		</ul>
	</div>
	<div class="copy_right"> &copy; chokcoco </div>
	<span class="footer__copyright"> 2014-2016. | 由<a href="https://hexo.io/"> Hexo </a>强力驱动 | 主题<a href="https://github.com/someus/huno"> Huno </a></span>

</footer>
<!-- 多说公共JS代码 start -->
<script type="text/javascript">
var duoshuoQuery = {short_name:"sbco"};
	(function() {
		var ds = document.createElement('script');
		ds.type = 'text/javascript';ds.async = true;
		ds.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') + '//static.duoshuo.com/embed.js';
		ds.charset = 'UTF-8';
		(document.getElementsByTagName('head')[0]
		 || document.getElementsByTagName('body')[0]).appendChild(ds);
	})();
</script>
<!-- 多说公共JS代码 end -->
<!-- cnzz统计 -->
<script type="text/javascript">
	var cnzz_protocol = (("https:" == document.location.protocol) ? " https://" : " http://");
	document.write(unescape("%3Cspan id='cnzz_stat_icon_1259441963'%3E%3C/span%3E%3Cscript src='" + cnzz_protocol + "s4.cnzz.com/z_stat.php%3Fid%3D1259441963' type='text/javascript'%3E%3C/script%3E"));
</script>
<!-- 文章阅读数统计 -->
<script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>
<!-- 百度爬虫推送 -->
<script>
(function(){
    var bp = document.createElement('script');
    var curProtocol = window.location.protocol.split(':')[0];
    if (curProtocol === 'https') {
        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
    }
    else {
        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
    }
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(bp, s);
})();
</script>

      </div>
    </div>
    <!-- js files -->
    <script src="/js/jquery.min.js"></script>
    <script src="/js/main.js"></script>
    <script src="/js/scale.fix.js"></script>
    
    

    <script type="text/javascript" src="//cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
    <script type="text/javascript"> 
        $(document).ready(function(){
            MathJax.Hub.Config({ 
                tex2jax: {inlineMath: [['[latex]','[/latex]'], ['\\(','\\)']]} 
            });
        });
    </script>


    

    <script src="/js/awesome-toc.min.js"></script>
    <script>
        $(document).ready(function(){
            $.awesome_toc({
                overlay: true,
                contentId: "post-content",
            });
        });
    </script>


    
    
    <!--kill ie6 -->
<!--[if IE 6]>
  <script src="//letskillie6.googlecode.com/svn/trunk/2/zh_CN.js"></script>
<![endif]-->
</body>
</html>
